package com.daidai.wordcount;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class WC {
    public static void main(String[] args) throws Exception {

        ExecutionEnvironment environment = ExecutionEnvironment.getExecutionEnvironment();

        DataSource<String> source = environment.readTextFile("data/wc.txt");

        AggregateOperator<Tuple2<String, Long>> sum =
                source.flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
                            String[] str = line.split(" ");
                            for (String s : str) {
                                out.collect(Tuple2.of(s, 1L));
                            }
                        }).returns(Types.TUPLE(Types.STRING, Types.LONG))
                        .groupBy(0)
                        .sum(1);

        sum.print();

    }
}
